﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;
using HomeFramework.Model;
using System.Runtime.Serialization;
using System.Transactions;

namespace HomeFramework.Services
{
    [DataContract]
    public class HandlerDTO
    {
        [DataMember]
        public byte[] AssemblyRawData { get; set; }

        [DataMember]
        public byte[][] ReferencesRawData { get; set; }
    }

    [ServiceContract]
    public interface IManagerService
    {
        [OperationContract]
        [FaultContract(typeof(string))]
        void AddHandler(HandlerDTO arg);
    }

    [ServiceBehavior]
    public class ManagerService : IManagerService
    {
        [OperationBehavior]
        public void AddHandler(HandlerDTO arg)
        {
            try
            {
                var ts = new TransactionScript();
                var ha = Handler.Utility.ReadAssembly(arg.AssemblyRawData);
                var rf = new List<Reference>();

                foreach (var r in arg.ReferencesRawData)
                    rf.Add(Handler.Utility.ReadReference(r));

                using (var t = new TransactionScope())
                {
                    foreach (var h in ha)
                    {
                        var newh = ts.AddHandler(h);
                        foreach (var r in rf)
                            ts.AddReference(r, newh.ID);
                    }

                    t.Complete();
                }
            }
            catch (Exception ex)
            {
                throw new FaultException<string>(ex.Message);
            }
        }
    }
}